package com.heima.serach.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.es.service.EsService;
import com.heima.model.article.pojos.ApUser;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.serach.dtos.UserSearchDTO;
import com.heima.model.serach.vos.SearchArticleVO;
import com.heima.model.treadlocal.AppThreadLocalUtils;
import com.heima.serach.service.ApUserSearchService;
import com.heima.serach.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    public static final String APP_INFO_ARTICLE = "app_info_article";

    /**
     * 前端根据关键词查询搜索
     * @param userSearchDto
     * @return
     */

    @Autowired
    EsService<SearchArticleVO> esService;

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    ApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(UserSearchDTO userSearchDto) {
        //1. 检查参数
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto == null || StringUtils.isBlank(searchWords)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if(user !=null) userSearchDto.setEntryId(user.getId());
     apUserSearchService.insert(userSearchDto);


        //2.构建es的创造条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //2 . 1 创建布尔请求
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //2 . 2 根据关键词 ， 使用match分词，  并使用title字段

        boolQuery.must(QueryBuilders.matchQuery("title" , searchWords));
        //2.3 个人那句前端传过来的最小时间， 进行range查询
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime()));

        sourceBuilder.query(boolQuery);
        //2.4设置高亮条件 ， 那个字段， 前置后置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);
        //2.5按照发布时间倒序
         sourceBuilder.sort("publishTime" , SortOrder.DESC);
        //2.6 设置分页
        sourceBuilder.size(userSearchDto.getPageSize());
        //3 . 调用es工具类search方法，查询索引库
        PageResponseResult searchResult = esService.search(sourceBuilder, SearchArticleVO.class, APP_INFO_ARTICLE);
        //拼接静态页前缀

        List<SearchArticleVO> SearchArticlVoList = (List<SearchArticleVO>) searchResult.getData();

        if (CollectionUtils.isNotEmpty(SearchArticlVoList)){
            for (SearchArticleVO searchArticleVO : SearchArticlVoList) {
                searchArticleVO.setStaticUrl(readPath+searchArticleVO.getStaticUrl());
            }
        }
        return searchResult;
    }
}
